var bcrypt = dcodeIO.bcrypt; // 使用bcrypt库

function signup() {
    const name = document.getElementById('newname').value;
    const email = document.getElementById('newemail').value;
    const password1 = document.getElementById('newpassword1').value;
    const password2 = document.getElementById('newpassword2').value;

    if (!document.getElementById('agreeTerms').checked) {
        alert('Please agree to the terms of service before registering.');
        return;
    }

    if (password1 === password2) {
        const salt = bcrypt.genSaltSync(10);
        const hashedPassword = bcrypt.hashSync(password1, salt);

        let users = JSON.parse(localStorage.getItem("users"));
        if (users === null) {
            users = [];
        }
        users.push({ name, email, password: hashedPassword });
        localStorage.setItem("users", JSON.stringify(users));
        alert('User registered with hashed password. Welcome'+ name);
        window.location.href = "./login.html";
    } else {
        alert('Passwords do not match!');
    }
}

function login() {
    const users = JSON.parse(localStorage.getItem("users"));
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    const currentTime = new Date().toLocaleString();

    const user = users.find(u => u.email === email);
    if (user && bcrypt.compareSync(password, user.password)) {
        if (!user.loginTimes) {
            user.loginTimes = [];
        }
        user.loginTimes.push(currentTime);
        localStorage.setItem("users", JSON.stringify(users));
        
        alert('Login successful! for'+ user.name);
        localStorage.setItem("loggedinUser", JSON.stringify(user));
        window.location.href = "./index.html";
    } else {
        alert('Login failed.');
    }
}


var user = JSON.parse(localStorage.getItem("loggedinUser"));
if (user) {
    console.log("Currently logged in: " + user["name"]);
    document.getElementById("name-goes-here").innerText = user["name"];
} else {
    console.log("No one is logged in");
}